#include "lcstate.h"

#include <iostream>
using namespace std;


LCState::LCState(const char* lcdir){
	int err;
	L = lua_open();
	luaL_openlibs(L);  /* open libraries */
	
	char fname[strlen(lcdir)+strlen("luacalc.lua")+2];
	sprintf(fname, "%s%s", lcdir, "/luacalc.lua");

	cout << fname << endl;


	char path[strlen("./?.lua;./?.lc;")+strlen(lcdir)+strlen("/?.lua")+1];
	sprintf(path, "./?.lua;./?.lc;%s/?.lua", lcdir);
	lua_getfield(L, LUA_GLOBALSINDEX, "package");
	lua_pushstring(L, path);
	lua_setfield(L, -2, "path");
	lua_pop(L, 1);



	/* load the file. */
	if ((err=luaL_loadfile(L, fname))==0){
		// Push the function name onto the stack
		if ((err = lua_pcall (L, 0, LUA_MULTRET, 0)) == 0){
			lua_pushstring (L, "hello");
			// Function is located in the Global Table
			lua_gettable (L, LUA_GLOBALSINDEX);
			lua_pcall (L, 0, 0, 0);
		}else{
			cerr << "couldn't load main: " << lua_tostring(L, lua_gettop(L)) << endl;
			exit(1);
		}
	}else{
		std::cerr << "couldn't load file: " << lua_tostring(L, lua_gettop(L)) << endl;
		exit(2);
	}


}

LCState::~LCState(){
	lua_close(L);
}

int LCState::GetTop(){
	return lua_gettop(L);
}


int main(int argc, const char* argv[]){
	if (argc <= 1) return 1;
	LCState* lua = new LCState(argv[1]);
	delete lua;
	return 0;

}
